package io.renren.service.impl;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.Query;
import io.renren.dao.BalanceDetailDao;
import io.renren.entity.BalanceDetailEntity;
import io.renren.service.BalanceDetailService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("balanceDetailService")
public class BalanceDetailServiceImpl extends ServiceImpl<BalanceDetailDao, BalanceDetailEntity> implements BalanceDetailService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Long memberId = (Long) params.get("id");
		Page<BalanceDetailEntity> page = this.selectPage(new Query<BalanceDetailEntity>(params).getPage(), new EntityWrapper<BalanceDetailEntity>().eq(memberId != null, "member_id", memberId).orderBy("create_time", false));

		return new PageUtils(page);
	}

	@Override
	public double myProfit(Long memberId, Date startDate) {
		List<Map<String, Object>> list = this.selectMaps(new EntityWrapper<BalanceDetailEntity>().setSqlSelect("type,ifnull(sum(cast(balance_change as decimal(18,4))),0) balanceChange").eq("member_id", memberId).ge("create_time", startDate).groupBy("type"));
		BigDecimal profit = new BigDecimal("0");
		if (CollectionUtils.isNotEmpty(list)) {
			for (Map<String, Object> map : list) {
				Integer type = (Integer) map.get("type");
				BigDecimal balanceChange = (BigDecimal) map.get("balanceChange");
				if (type == ProjectConstant.ORDER_TYPE_SEND_PACKET) {
					profit = profit.add(balanceChange);
				} else if (type == ProjectConstant.ORDER_TYPE_GRAB_PACKET) {
					profit = profit.add(balanceChange);
				} else if (type == ProjectConstant.ORDER_TYPE_LANDMINE) {
					profit = profit.add(balanceChange);
				} else if (type == ProjectConstant.ORDER_TYPE_RETURN) {
					profit = profit.add(balanceChange);
				}
			}
		}
		return profit.doubleValue();
	}
}
